package vn.gq.tym.widget;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.actionbarsherlock.app.SherlockFragment;

public abstract class BaseFragment extends SherlockFragment {
	
	protected View mLayout;
	
	public abstract int getLayoutId();
	
	public abstract int getContainerId();
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (mLayout == null) {
			mLayout = inflater.inflate(getLayoutId(), container, false);
			createView(savedInstanceState);
		} else {
			((ViewGroup) mLayout.getParent()).removeView(mLayout);
		}
		return mLayout;
	}
	
	public abstract void createView(Bundle savedInstanceState);

	protected View findViewById(int resId) {
		return mLayout.findViewById(resId);
	}
	
	public void startFragment(int containerId, BaseFragment fragment, String tag) {
		startFragment(containerId, fragment, tag, true);
	}
	
	public void startFragment(int containerId, BaseFragment fragment, String tag, boolean backToPrevious) {
		FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
		ft.detach(this);
		ft.add(containerId, fragment, tag);
		// if backToPrevious set true, when press back fragment will back to previous fragment before
		if (backToPrevious)
			ft.addToBackStack(null);
		ft.commit();
	}
	
	public String getFragmentTag() {
		return getClass().getSimpleName() + hashCode();
	}
	
	public void onResume() {
		super.onResume();
		if (getActivity() instanceof ITabHost) {
			((ITabHost) getActivity()).setCurrentFragment(this);
		}
	}
}
